/*
 * givebackmgr.cpp
 *
 *  Created on: Jun 23, 2014
 *      Author: killerg
 */

#include "../server_deps.h"
#include "../server.h"
#include "../server_cfg.h"

#include "givebackmgr.h"
#include "player_mgr.h"
#include "mail_mgr.h"

#include "share/util.h"


bool giveback_mgr_t::init() {
    std::string cfg_path = fmt_cstr("%s/cfg/giveback.txt", get_deploy());
    Json::Value cfg;
    const char* cfg_file = load_file(cfg_path.c_str());
    if (NULL == cfg_file)
        return false;

    const auto load = to_json(cfg_file);
    for (auto &reward : load) {
    	slot_t slot;
    	slot.playerid = reward["playerid"].asInt();
    	slot.code = reward["code"].asCString();
    	slot.account = reward["account"].asCString();
    	slot.group = reward["group"].asInt();

    	rewards.push_back(slot);
    }

    cur_index = -1;

	return true;
}
void giveback_mgr_t::destroy() {

}
void giveback_mgr_t::update() {
	for (int i=0; i<100 && need_reward(); ++i) {
		reward_once();
	}
}

bool giveback_mgr_t::need_reward() {
	return cur_index >= 0 && cur_index < rewards.size();
}

bool giveback_mgr_t::reward_once() {
	if (cur_index >= rewards.size())
		return false;

	int64_t playerid = rewards[cur_index].playerid + g_cfg->ServerId * int64_t(co::MaxAccountNum);
	string code = rewards[cur_index].code;
	string account = rewards[cur_index].account;
	++cur_index;

	string text;
	if (rewards[cur_index].group >= 5)
		text = fmt_cstr("感谢对宠物战记的支持，恭喜您获得全民斗兽兑换码:%s，请联系客服QQ:79608063兑换全民斗兽激活码，请在全民斗兽1区使用", code.c_str());
	else
		text = fmt_cstr("感谢对宠物战记的支持，恭喜您获得全民斗兽激活码:%s，请在全民斗兽1区使用", code.c_str());

	auto info = g_playermgr->infos.get(playerid);
	if (info) {
		g_mail->send_person(playerid, -1, text, [playerid, code, account](bool ok){
			if (!ok) {
				UTIL_LOG(E, "account:%s playerid:%lld code:%s not send", account.c_str(), playerid, code.c_str());
			}
		});

		return true;
	}

	return false;
}
